package com.nf.nf.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 公共工具类 公用的工具类如字符串处理、时间处理等
 * 
 * @author 章隆敏
 * @version [1.0, 2017年1月6日]
 * @since [pcloud/2.0]
 */
public class GlobalUtil {
	protected final static Logger logger = Logger.getLogger(GlobalUtil.class);
    /**
     * 判断Object引用为null或者值为空
     * 
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj instanceof Object[]) {
            Object[] o = (Object[]) obj;
            for (int i = 0; i < o.length; i++) {
                Object object = o[i];
                if ((object == null) || (("").equals(object)) || ("null".equals(obj))) {
                    return true;
                }
            }
        } else if (obj instanceof Collection) {
            @SuppressWarnings("rawtypes")
            Collection o = (Collection) obj;
            if (o == null || o.isEmpty()) {
                return true;
            }
        } else {
            if ((obj == null) || (("").equals(obj)) || ("null".equals(obj))) {
                return true;
            }
        }

        return false;
    }
    /**
     * 生产位随机数字
     * @return
     */
	public static int random6int(){
		return (int)((Math.random()*9+1)*100000);
	}
    /**
     * 将时间转换为int类型
     * 
     * @param timeString
     * @param format
     * @return
     */
    public static int DateToInt(String timeString, String format) {

        int time = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(timeString);
            String strTime = date.getTime() + "";
            strTime = strTime.substring(0, 10);
            time = Integer.parseInt(strTime);

        } catch (ParseException e) {
            logger.error("error", e);
        }
        return time;
    }

    /**
     * 将时间转换为long类型
     * 
     * @param timeString
     * @param format
     * @return
     */
    public static long DateToLong(String timeString, String format) {

        Long time = 0L;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(timeString);
            String strTime = date.getTime() + "";
            time = Long.parseLong(strTime);
        } catch (ParseException e) {
            logger.error("error", e);
        }
        return time;
    }

    /**
     * @methodName: DateToInt2
     * @description: 将时间转换为int类型
     * <br/>
      * @param timeDate
     * @return int
     * @author cris
     * @date 2018/11/2 11:16
     */
    public static int DateToInt2(Date timeDate) {

        int time = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timeString = sdf.format(timeDate);
            Date date = sdf.parse(timeString);
            String strTime = date.getTime() + "";
            strTime = strTime.substring(0, 10);
            time = Integer.parseInt(strTime);

        } catch (ParseException e) {
            logger.error("error", e);
        }
        return time;
    }

    /**
     * @methodName: IntToDate
     * @description: 将时间戳转换为Date类型
     * <br/>
      * @param time
     * @return java.util.Date
     * @author cris
     * @date 2018/11/2 11:16
     */
    public static Date IntToDate(String time) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long timeDate = new Long(time);
        String d = format.format(timeDate * 1000);
        Date date = format.parse(d);
        return date;
    }
    
    /**
     * @methodName: LongToDate
     * @description: 将时间戳转换为Date类型
     * <br/>
      * @param time
     * @return java.util.Date
     * @author cris
     * @date 2018/11/2 11:16
     */
    public static Date LongToDate(String time) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long timeDate = new Long(time);
        if (time.length()==10) {
        	timeDate=timeDate*1000;
		}
        String d = format.format(timeDate);
        Date date = format.parse(d);
        return date;
    }
    
    /**
     * @methodName: LongToTime
     * @description: 将时间戳转换为Date类型
     * <br/>
      * @param time
     * @return java.lang.String
     * @author cris
     * @date 2018/11/2 11:17
     */
    public static String LongToTime(String time){
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        Long timeDate = new Long(time);
        if (time.length()==10) {
        	timeDate=timeDate*1000;
		}
        String d = format.format(timeDate);
        return d;
    }

    /**
     * 将date类型转化为yyyy-MM-dd HH:mm:ss格式字符串
     * 
     * @param date
     * @return
     */
    public static String getDate8String(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 将时间long转换为String类型
     * 
     * @param date
     *            long
     * @return
     */
    public static String getDate10String(int date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(((long) date) * 1000);
    }
    
    /**
     * 将时间long转换为String类型
     * 
     * @param date
     *            long
     * @return
     */
    public static String getDateString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * @Method: makeFileName
     * @Description: 生成上传文件的文件名，文件名以：uuid+"_"+文件的原始名称
     * @param filename
     *            文件的原始名称
     * @return uuid+"_"+文件的原始名称
     */
    public static String makeFileName(String filename) { // 2.jpg
        // 为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /**
     * 系统当前时间加d天
     * 
     * @param d
     *            天数
     * @return
     */
    public static Date calendarAddxD(int d) {
        // 当前日期-3天
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, +d);
        return cal.getTime();
    }

    /**
     * 系统当前时间减d天
     * 
     * @param d
     *            天数
     * @return
     */
    public static Date calendarminusxD(int d) {
        // 当前日期-3天
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -d);
        return cal.getTime();
    }

    /**
     * yyyy-MM-dd HH:mm:ss字符串转换为时间
     * 
     * @param sDate
     * @return
     */
    public static Date getDate7String(String sDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date obj = null;
        try {
            obj = sdf.parse(sDate);
        } catch (ParseException e) {
            logger.error("error", e);
        }
        return obj;
    }
    public static Date getDateFromString(String sDate,String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date obj = null;
        try {
            obj = sdf.parse(sDate);
        } catch (ParseException e) {
            logger.error("error", e);
        }
        return obj;
    }

    /**
     * 得到某年某月的最后一天
     * 
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, value);
        return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());

    }

    /**
     * 得到某年某月的第一天
     * 
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    }

    /**
     * @methodName: isCurrentData
     * @description: 判断是否为真实值
     */
    public static boolean isCurrentData(Long data,String frequency) {
        long now = System.currentTimeMillis();
        // 时间差在一分钟内，为信号正常，否则默认信号中断 TODO暂时设置20分钟
        if (now - data < Long.valueOf(frequency)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @methodName: getPointRealData
     * @description: 根据值含义对照关系，获取测点值
     * <br/>
      * @param value
     * @param valueMean
     * @return java.lang.String
     * @author cris
     * @date 2018/11/2 11:18
     */
    public static String getPointRealData(String value, String valueMean) {
        String[] vm = valueMean.split(",");
        String result = "";
        for (String val : vm) {
            if (value.equals(val.split(":")[0])) {
                result = val.split(":")[1];
            }
        }
        return result;
    }

    /**
     * 获取上一月
     * 
     * @return yyyyMM
     */
    public static String getLastMonth() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String time = format.format(c.getTime());
        return time;
    }

    /**
     * 获取上一季度
     * 
     * @return yyyyMM
     */
    public static String getLastSeason() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -3);
        SimpleDateFormat formatm = new SimpleDateFormat("MM");
        SimpleDateFormat formaty = new SimpleDateFormat("yyyy");
        String month = formatm.format(c.getTime());
        String year = formaty.format(c.getTime());
        String season = "";
        if (month.equals("01") || month.equals("02") || month.equals("03")) {
            season = "Q1";
        } else if (month.equals("04") || month.equals("05") || month.equals("06")) {
            season = "Q2";
        } else if (month.equals("07") || month.equals("08") || month.equals("09")) {
            season = "Q3";
        } else {
            season = "Q4";
        }
        return year + season;
    }

    /**
     * 获取上一年
     * 
     * @return yyyy
     */
    public static String getLastYear() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        String time = format.format(c.getTime());
        return time;
    }

    /**
     * 获取上一年
     * 
     * @return yyyy
     */
    public static String getMonthLastDay(int year, int month) {
        Calendar cal = Calendar.getInstance();
        // 不加下面2行，就是取当前时间前一个月的第一天及最后一天
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date lastDate = cal.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String time = format.format(lastDate);
        return time;
    }

    @SuppressWarnings("resource")
	public static long copyFile(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                return new Date().getTime() - time;
            }
            if ((inC.size() - inC.position()) < 20971520)
                length = (int) (inC.size() - inC.position());
            else
                length = 20971520;
            inC.transferTo(inC.position(), length, outC);
            inC.position(inC.position() + length);
        }
    }
    
    /**
     * 字符串转decimal类型
     * 
     * @param str
     *         带转换的字符串
     * @param scale
     *         小数点保留位数
     * @return       
     */
    public static BigDecimal str2Decimal(String str, int scale) {
        if (str == null || "".equals(str)) {
            return BigDecimal.ZERO;
        }
        BigDecimal decimal = new BigDecimal(str);
        return decimal.setScale(scale, BigDecimal.ROUND_HALF_UP);
    }
    
    public static BigDecimal decimalDiv(BigDecimal a, BigDecimal b, int scale) {
        if (b == null || b.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        return a.divide(b, scale, BigDecimal.ROUND_HALF_UP);
    }
    /** 
     * 删除单个文件 
     * @param   sPath    被删除文件的文件名 
     * @return 单个文件删除成功返回true，否则返回false 
     */  
    public static boolean DeleteFolder(String sPath) {  
        Boolean flag = false;  
        File file = new File(sPath);  
     // 判断目录或文件是否存在  
        if (!file.exists()) {  // 不存在返回 false  
            return flag;  
        } else {  
            // 判断是否为文件  
            if (file.isFile()) {  // 为文件时调用删除文件方法  
                return deleteFile(sPath);  
            } else {  // 为目录时调用删除目录方法  
                return deleteDirectory(sPath);  
            }  
        }  
    }  
    /** 
     * 删除目录（文件夹）以及目录下的文件 
     * @param   sPath 被删除目录的文件路径 
     * @return  目录删除成功返回true，否则返回false 
     */  
    public static boolean deleteDirectory(String sPath) {  
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符  
        if (!sPath.endsWith(File.separator)) {  
            sPath = sPath + File.separator;  
        }  
        File dirFile = new File(sPath);  
        //如果dir对应的文件不存在，或者不是一个目录，则退出  
        if (!dirFile.exists() || !dirFile.isDirectory()) {  
            return false;  
        }  
        boolean  flag = true;  
        //删除文件夹下的所有文件(包括子目录)  
        File[] files = dirFile.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            //删除子文件  
            if (files[i].isFile()) {  
                flag = deleteFile(files[i].getAbsolutePath());  
                if (!flag) break;  
            } //删除子目录  
            else {  
                flag = deleteDirectory(files[i].getAbsolutePath());  
                if (!flag) break;  
            }  
        }  
        if (!flag) return false;  
        //删除当前目录  
        if (dirFile.delete()) {  
            return true;  
        } else {  
            return false;  
        }  
    }  
    /** 
     * 删除单个文件 
     * @param   sPath    被删除文件的文件名 
     * @return 单个文件删除成功返回true，否则返回false 
     */  
    public static boolean deleteFile(String sPath) {  
        boolean flag = false;  
        File file = new File(sPath);  
        // 路径为文件且不为空则进行删除  
        if (file.isFile() && file.exists()) {  
            file.delete();  
            flag = true;  
        }  
        return flag;  
    }  
    
    public static String getRemoteAddrIp(HttpServletRequest request) {
        String ipFromNginx = getHeader(request, "X-Real-IP");
//        System.out.println("ipFromNginx:" + ipFromNginx);
//        System.out.println("getRemoteAddr:" + request.getRemoteAddr());
        return isNullOrEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
    }


    private static String getHeader(HttpServletRequest request, String headName) {
        String value = request.getHeader(headName);
        return !StringUtils.isEmpty(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
    }
    public static String getIpAddr(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        
        
     // 获取ip地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
               }
               if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                   ip = request.getHeader("HTTP_X_FORWARDED_FOR");
               }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
                // 因为有些有些登录是通过代理，所以取第一个（第一个为真是ip）
                int index = ip.indexOf(',');
                if (index != -1) {
                    ip = ip.substring(0, index);
               }
        return ip;
    }
    
    public static void main(String[] args) {
        // String Stations="(001,002)";
        // String[] stas=Stations.replace("(", "").replaceAll(")",
        // "").split(",");
        // System.out.println(stas);
        // System.out.println(DateToLong("2016-01-12 12:25:12","yyyy-MM-dd HH:mm:ss"));
//        File f1 = new File("D:/发改委污水处理项目资料/运营分析/test/报告模板.xlsx");
//        File f2 = new File("D:/发改委污水处理项目资料/运营分析/test/报告模板tteetetet.xlsx");
//        try {
//            copyFile(f1, f2);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            logger.error("error", e);
//        }
    	DeleteFolder("D:/upload/unit/add/admin/20170713174938/");
//        System.out.println("----------resuult---------" + getMonthLastDay(2016, 2));
    }
}
